package cn.sciento.boot.tenant.feign.impl;

import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.RequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
import cn.sciento.boot.tenant.feign.DynamicFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

@Service
@Import({FeignClientsConfiguration.class})
public class DynamicFeignServiceImpl implements DynamicFeignService {
  private final Feign.Builder urlBuilder;
  
  private final Feign.Builder nameBuilder;
  
  @Autowired
  public DynamicFeignServiceImpl(Decoder decoder, Encoder encoder, Client client, Contract contract, RequestInterceptor requestInterceptor) {
    this.nameBuilder = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract).requestInterceptor(requestInterceptor);
    if (client instanceof LoadBalancerFeignClient)
      client = ((LoadBalancerFeignClient)client).getDelegate(); 
    this.urlBuilder = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract).requestInterceptor(requestInterceptor);
  }
  
  public <T> T newInstanceByUrl(Class<T> apiType, String url) {
    return (T)this.urlBuilder.target(apiType, url);
  }
  
  public <T> T newInstanceByName(Class<T> apiType, String name) {
    return (T)this.nameBuilder.target(apiType, name);
  }
}
